package network;

import java.util.ArrayList;
import java.util.HashMap;

public class Device {
    public static int cnt = 0;
    public int uid;

    private String name;
    private Trie rules;
    private HashMap<String, Port> nameToPort = new HashMap<>();

    public Device(String name) {
        this.name = name;
        this.rules = new Trie();

        if (!name.equals("default")) {
            this.uid = Device.cnt;
            Device.cnt ++;
        }
    }

    /**
     * Similar to Network, the clone copies everything except rules.
     * @return an instance of device with an identical Trie
     */
    public Device clone() {
        Device ret = new Device(name);
        ret.nameToPort = (HashMap<String, Port>) this.nameToPort.clone();
        return ret;
    }

    public Port addPortByName(String name) {
        Port p = new Port(name, this);
        this.nameToPort.put(name, p);
        return p;
    }

    public Port getPortByName(String name) {
        if (!this.nameToPort.containsKey(name)) {
            this.nameToPort.put(name, new Port(name, this));
        }
        return this.nameToPort.get(name);
    }

    public String getName() {
        return this.name;
    }

    public ArrayList<Rule> addAndGetAllUntil(Rule rule) {
        return this.rules.addAndGetAllOverlappingWith(rule);
    }

    @Override
    public String toString() {
        return this.getName();
    }
}
